package com.minisoft.controller;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import com.alibaba.dashscope.app.*;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@Slf4j
@RequestMapping("/api")
public class StreamController {

    // 假设这是你的节点名称列表
    private static final List<String> nodeNames = ListUtil.of(
            "敏感话题负面情绪-低成本模型",
            "项目楼盘信息介绍",
            "楼盘信息联网-发散性-高质量模型",
            "项目活动介绍-非发散性-低成本模型"
    );
    ExecutorService executor = Executors.newSingleThreadExecutor();
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseBodyEmitter streamData() {
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();

        executor.execute(() -> {
            try {
                // 模拟调用智能体应用
                ApplicationParam param = ApplicationParam.builder()
                        .apiKey("sk-837018ca105a4629ac23b8545d3c844a") // 示例API Key
                        .appId("adbdbd6a2100413283fac3b64eddb210") // 示例App ID
                        .prompt("使用java") // 示例提示
                        .parameter("flow_stream_mode", "full_thoughts")
                        .hasThoughts(true) // 启用流式输出
                        .build();

                Application application = new Application();
                Flowable<ApplicationResult> result = application.streamCall(param);

                StringBuilder previousReasoningContent = new StringBuilder();
                StringBuilder previousResultContent = new StringBuilder();

                result.blockingForEach(data -> {
                    if (data.getOutput().getThoughts() != null) {
                        data.getOutput().getThoughts().forEach(thought -> {
                            JSONObject response = JSONUtil.parseObj(thought.getResponse());
                            String nodeType = response.getStr("nodeType"); // 节点类型
                            String nodeName = response.getStr("nodeName"); // 节点名称

                            if (nodeNames.contains(nodeName)) {
                                JSONObject nodeResult = response.getJSONObject("nodeResult");
                                if (nodeResult != null) {
                                    String reasoningContent = nodeResult.getStr("reasoningContent");
                                    String resultText = nodeResult.getStr("result");

                                    if (StrUtil.isNotBlank(resultText)) {
                                        if (previousResultContent.length() == 0) {
                                            sendMsg(emitter,"开始回答");
                                        }
                                        String newDelta = resultText.substring(previousResultContent.length());
                                        sendMsg(emitter,newDelta); // 流式输出结果内容
                                        previousResultContent.append(newDelta);
                                    } else {
                                        if (previousReasoningContent.length() == 0) {
                                            sendMsg(emitter,"开始推理过程");
                                        }
                                        String newDelta = reasoningContent.substring(previousReasoningContent.length());
                                        sendMsg(emitter,newDelta);
                                        previousReasoningContent.append(newDelta);
                                    }
                                }
                            }
                        });
                    }
                });

                emitter.complete(); // 完成流式传输
            } catch (Exception e) {
                emitter.completeWithError(e); // 处理异常
            } finally {
                executor.shutdown();
            }
        });

        return emitter;
    }

    private static void sendMsg(ResponseBodyEmitter emitter,String msg){
        try {
            emitter.send(msg);
        } catch (Exception e) {
            log.error("sendMsg error", e);
            emitter.completeWithError(e);
        }
    }


}